package com.thinkit.bigdata.web.controller.tagging;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.core.util.excel.XlsUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.es.audioEs.VoiceInfoDto;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.impl.audioSearch.AudioSearchPubMetImpl;
import com.thinkit.bigdata.web.service.tagging.TaggingService;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tagging")
public class TaggingController {

    private static Logger logger = Logger.getLogger(TaggingController.class);

    @Resource
    private TaggingService taggingService;

    @Resource
    private ESUtil esUtil;

    //标签列表展示 - list
    @RequestMapping(value = "/tagging-list", method = RequestMethod.POST)
    public HtmlResult getTaggingList(@RequestParam(value = "serialNumber") final String serialNumber) {
        String logTxt = "【标签列表展示】";
        logger.info(logTxt);
        logger.info(logTxt + "serialNumber = " + serialNumber);
        return taggingService.getTaggingList(serialNumber);

    }//标签详情列表展示 - list

    @RequestMapping(value = "/tagging-mes-list", method = RequestMethod.POST)
    public HtmlResult getTaggingMesList(
            @RequestParam(value = "serialNumber") final String serialNumber,
            @RequestParam(value = "tagId") final String tagId
    ) {
        String logTxt = "【标签详情列表展示】";
        logger.info(logTxt);
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "tagId = " + tagId);
        return taggingService.getTaggingMesList(serialNumber, tagId);
    }

    //判错操作
    @RequestMapping(value = "/judge-tagging-error", method = RequestMethod.POST)
    public HtmlResult judgeTaggingError(
            @RequestParam(value = "serialNumber") final String serialNumber,
            @RequestParam(value = "tagId") final String tagId,
            @RequestParam(value = "matchStatus") final Integer matchStatus,
            @RequestParam(value = "proNote") final String proNote,
            @RequestParam(value = "startTime") final String startTime,
            @RequestParam(value = "endTime") final String endTime
    ) {
        String logTxt = "【标签判错操作】";
        logger.info(logTxt);
        logger.info(logTxt + "serialNumber = " + serialNumber);
        logger.info(logTxt + "tagId = " + tagId);
        logger.info(logTxt + "matchStatus = " + matchStatus);
        logger.info(logTxt + "proNote = " + proNote);
        logger.info(logTxt + "startTime = " + startTime);
        logger.info(logTxt + "endTime = " + endTime);
        return taggingService.judgeTaggingError(serialNumber, tagId, matchStatus, proNote, startTime, endTime);
    }

    //统计 - 不分页 - 可以选择父级节点
    @RequestMapping(value = "/tagging-statistics", method = RequestMethod.POST)
    public HtmlResult taggingStatistics(HttpServletRequest request) {
        String logTxt = "【标签标注统计】";
        logger.info(logTxt);
        String callStartTime = request.getParameter("callStartTime");
        if (Strings.isNullOrEmpty(callStartTime)) {
            return HtmlResult.failure("通话时间为空");
        }
        return HtmlResult.success(taggingService.taggingStatistics(request, logTxt));
    }

    //统计导出
    @RequestMapping(value = "/export-tagging-statistics", method = RequestMethod.POST)
    public void exportTaggingStatistics(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【标签标注统计-导出】";
        logger.info(logTxt);
        try {
            List<Map<String, Object>> resultList = taggingService.taggingStatistics(request, logTxt);
            logger.info("获取数据条数为：" + resultList.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "省份", "系统标签", "语义匹配量", "语义错误量", "匹配错误率"};
            String title = "标签标注统计表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < resultList.size(); j++) {
                Map<String, Object> source = resultList.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(source.get("provinceCode").toString()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(source.get("tagName").toString()));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(source.get("allTagNum").toString()));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(source.get("errorTagNum").toString()));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(source.get("successTagNum").toString()));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            logger.info(logTxt + "异常");
        }
    }

    //统计导出明细
    @RequestMapping(value = "/export-tagging-statistics-mes", method = RequestMethod.POST)
    public void exportTaggingStatisticsMes(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【标签标注统计明细-导出】";
        logger.info(logTxt);
        try {
            List<Map<String, String>> resultList = taggingService.getExportDate(request, logTxt);
            logger.info("获取数据条数为：" + resultList.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "省份", "流水号", "命中时间段", "句子", "匹配状态", "处理备注", "处理时间"};
            String title = "标签标注统计信息表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < resultList.size(); j++) {
                Map<String, String> source = resultList.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(source.get("provinceCode")));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(source.get("serialNumber")));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(source.get("startTime") + " - " + source.get("endTime")));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(source.get("content")));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(source.get("matchStatus")));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(source.get("proNote")));
                            break;
                        case 7:
                            cell2.setCellValue(new HSSFRichTextString(source.get("proTime")));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            logger.info(logTxt + "异常");
        }
    }

    //导出打标错误标签明细
    @RequestMapping(value = "/export-error-tagging-statistics-mes", method = RequestMethod.POST)
    public void exportTaggingStatisticsErrorMes(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【标签语义错误匹配话单信息列表-导出】";
        logger.info(logTxt);
        try {
            String taggingError = request.getParameter("taggingError");
            if ("error".equals(taggingError)) {
                List<Map<String, String>> resultList = taggingService.getExportDate(request, logTxt);
                logger.info("获取数据条数为：" + resultList.size());
                //生成excel
                HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
                HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
                //设置标题和列名称
                String[] header = {"编号", "省份", "流水号", "命中时间段", "句子", "匹配状态", "处理备注", "处理时间"};
                String title = "标签语义错误匹配话单信息列表";
                XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
                //获取表文样式
                HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
                HSSFRow row2;
                HSSFCell cell2;
                for (int j = 0; j < resultList.size(); j++) {
                    Map<String, String> source = resultList.get(j);
                    row2 = sheet.createRow(3 + j);
                    for (int i = 0; i < header.length; i++) {
                        cell2 = row2.createCell(i);
                        cell2.setCellStyle(tableStyle);
                        switch (i) {
                            case 0:
                                cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                                break;
                            case 1:
                                cell2.setCellValue(new HSSFRichTextString(source.get("provinceCode")));
                                break;
                            case 2:
                                cell2.setCellValue(new HSSFRichTextString(source.get("serialNumber")));
                                break;
                            case 3:
                                cell2.setCellValue(new HSSFRichTextString(source.get("startTime") + " - " + source.get("endTime")));
                                break;
                            case 4:
                                cell2.setCellValue(new HSSFRichTextString(source.get("content")));
                                break;
                            case 5:
                                cell2.setCellValue(new HSSFRichTextString(source.get("matchStatus")));
                                break;
                            case 6:
                                cell2.setCellValue(new HSSFRichTextString(source.get("proNote")));
                                break;
                            case 7:
                                cell2.setCellValue(new HSSFRichTextString(source.get("proTime")));
                                break;
                        }
                    }
                }
                for (int i = 0; i < header.length; i++) {
                    sheet.autoSizeColumn((short) i, true);//自动调整列宽
                }
                String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
                // 清空response
                response.reset();
                response.setContentType("application/vnd.ms-excel");
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
                workbook.write(response.getOutputStream());
                return;
            }
            List<VoiceInfoDto> resultList = taggingService.getErrorExportDate(request, logTxt);
            logger.info("获取数据条数为：" + resultList.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "省份",  "呼叫类型", "录音流水", "坐席班组", "坐席工号",  "坐席姓名", "客户号码", "受理号码", "通话时长(秒)", "通话开始时间",
                    "通话结束时间", "语音入库时间", "挂机方", "是否重复来电", "满意度", "客户归属地", "客户星级", "重要客户"};
            String title = "标签语义匹配话单信息列表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < resultList.size(); j++) {
                VoiceInfoDto voiceInfo = resultList.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getProvince()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getCallDirection() == 0 ? "呼入" : "呼出"));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getSerialNumber()));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getSeatGroup()));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getSeatId()));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getSeatName()));
                            break;
                        case 7:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getCustomerNum()));
                            break;
                        case 8:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getProPhoneNum()));
                            break;
                        case 9:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getHoldDuration() + ""));
                            break;
                        case 10:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getCallStartTime()));
                            break;
                        case 11:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getCallEndTime()));
                            break;
                        case 12:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getInputTime()));
                            break;
                        case 13:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeOnHook(voiceInfo.getOnHook())));
                            break;
                        case 14:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getReCallFlag() == 0 ? "否" : "是"));
                            break;
                        case 15:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeSatisfaction(voiceInfo.getSatisfaction())));
                            break;
                        case 16:
                            Map<String,Object> map =  SystemStatic.PROVINCE_CITY_MAP;
                            Map<String, String> citys = (Map<String, String>) map.get(voiceInfo.getProvinceCode());
                            String city = citys.get(voiceInfo.getCustomerloc());
                            cell2.setCellValue(new HSSFRichTextString(Strings.isNullOrEmpty(city) ? voiceInfo.getCustomerloc() : city));
                            break;
                        case 17:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeCustomerLevel(voiceInfo.getCustomerLevel())));
                            break;
                        case 18:
                            String customerSign = "";
                            if (!Strings.isNullOrEmpty(voiceInfo.getCustomerSign())) {
                                customerSign = voiceInfo.getCustomerSign().equals("0") ? "否" : "是";
                            }
                            cell2.setCellValue(new HSSFRichTextString(customerSign));
                            break;
                        case 19:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getBusTags()));
                            break;
                        case 20:
                            cell2.setCellValue(new HSSFRichTextString(voiceInfo.getSysTags()));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(logTxt + "异常");
        }
    }

    @RequestMapping(value = "/get-data-by-mes", method = RequestMethod.POST)
    public HtmlResult searchData(HttpServletRequest request) {
        String logTxt = "【标签标注统计-音频列表方法】";
        logger.info(logTxt);
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String sortName = request.getParameter("sortName");//录音流水
        String sortOrder = request.getParameter("sortOrder");//录音流水
        logger.info(logTxt + "pageNum = " + pageNum);
        logger.info(logTxt + "pageSize = " + pageSize);
        logger.info(logTxt + "sortName = " + sortName);
        logger.info(logTxt + "sortOrder = " + sortOrder);
        try {
            return taggingService.searchData(request);
        } catch (Exception e) {
            logger.info(logTxt + Arrays.toString(e.getStackTrace()));
            return HtmlResult.failure("获取数据异常");
        }
    }

    @RequestMapping(value = "/export-data-mes", method = RequestMethod.POST)
    public void exportMyAss(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【话单信息-导出】";
        logger.info(logTxt);
        try {
            BoolQueryBuilder boolQuery = taggingService.getQuery(logTxt, request);
            new AudioSearchPubMetImpl().exportMyAss(logTxt, request, response, boolQuery, esUtil);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
